import base64
import json
import pickle
from datetime import date

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from haystack.views import SearchView

from apps.contents.models import ContentCategory
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from apps.goods.utils import get_breadcrumb
from utils.goods import get_categories, get_goods_specs
from utils.viewmixin import LoginMixin


class IndexView(View):
    def get(self, request):
        categories = get_categories()

        # 广告数据
        contents = {}
        # 所有广告分类
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        context = {
            'categories': categories,
            'contents': contents
        }
        return render(request, 'index.html', context)


class ListView(View):
    def get(self, request, category_id):
        # 1.接收参数
        page = request.GET.get("page")
        page_size = request.GET.get("page_size")
        ordering = request.GET.get("ordering")
        try:
            # 根据category_id查询出对象
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, "errmsg": "分类查询失败"})

        # 2.面包屑导航数据，
        breadcrumb = get_breadcrumb(category)

        # 3.分类商品的数据查询
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)

        # 获取分页的paginator
        paginator = Paginator(skus, page_size)
        # 获取第page页的数据
        page_skus = paginator.page(page)

        # 4.把商品的数据转为字典
        sku_list = []
        for sku in page_skus:
            sku_list.append({
                "id": sku.id,
                "name": sku.name,
                "price": sku.price,
                "default_image_url": sku.default_image.url,
            })

        # 获取分页的总页码
        count = paginator.num_pages

        # 5.返回json
        return JsonResponse({'code': 0, "errmsg": "ok", 'breadcrumb': breadcrumb, "list": sku_list, "count": count})


class HotGoodsView(View):
    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]

        # 序列化
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price
            })

        return JsonResponse({'code': 0, "errmsg": "ok", 'hot_skus': hot_skus})


class MySearchView(SearchView):
    def create_response(self):
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count

            })

        return JsonResponse(data_list, safe=False)


class DetailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        cateories = get_categories()
        breadcrumb = get_breadcrumb(sku.category)

        specs = get_goods_specs(sku)

        context = {
            'categories': cateories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': specs,
        }

        return render(request, 'detail.html', context)


class CategoryVisitCountView(View):
    def post(self, request, cat_id):
        # 1.接收分类id校验
        # 去数据库查询cat_id对应的分类是否存在GoodsCategory
        # 2.查看当天这个分类在数据库有没有记录
        today = date.today()
        try:
            goodsVisitCount = GoodsVisitCount.objects.get(category_id=cat_id, date=today)
        except:
            # 3.没有就创建新数据
            goodsVisitCount = GoodsVisitCount()

        try:
            # 4.有的话count+1
            goodsVisitCount.count += 1
            goodsVisitCount.date = today
            goodsVisitCount.category_id = cat_id
            goodsVisitCount.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "失败"})
        # 5.返回响应

        return JsonResponse({"code": 0, "errmsg": "ok"})


class UserBrowseHistory(LoginMixin, View):
    def post(self, request):
        # 取出登录的user对象
        user = request.user

        # 1.接收请求
        json_data = json.loads(request.body)

        # 2.获取参数 sku_id
        sku_id = json_data.get("sku_id")

        # 3.验证参数
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "没有这个商品"})

        # 4.连接redis
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()

        # 5.去重
        pl.lrem("history_%s" % user.id, 0, sku_id)
        # 6.保存到redis
        pl.lpush("history_%s" % user.id, sku_id)

        # 7.保存五条
        pl.ltrim("history_%s" % user.id, 0, 4)
        # 执行管道
        pl.execute()

        # 8.返回json
        return JsonResponse({"code": 0, "errmsg": "ok"})

    def get(self, request):
        # 1.获取用户id
        # 2.取出登录的user对象
        user = request.user

        # 3.连接redis
        redis_conn = get_redis_connection('history')

        # 4.redis获取历史浏览记录的商品id
        sku_ids = redis_conn.lrange('history_%s' % user.id, 0, -1)

        # 5.根据商品id获取商品sku对象，转为字典
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        # 6.返回json数据
        return JsonResponse({"code": 0, "errmsg": "ok", 'skus': skus})



